import axios from 'axios'
import { showToast, showDialog } from 'vant'
import { useUserStore } from '@/stores/store'
import router from '@/router'
// 创建axios实例
const request = axios.create({
  baseURL: '/api', // 设置基础URL
  timeout: 5000
})
// 请求拦截器
request.interceptors.request.use(
  config => {
    // 统一添加token
    const userStore = useUserStore()
    const token = userStore.token
    if (token&&config.url!=='/user/login'&&config.url!=='/user/register') {
      config.headers.token = token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 响应拦截器
request.interceptors.response.use(
  response => {
    const { code, msg, data } = response.data
    // 成功
   // console.log('Response:', response.data);
    
    if (code === 200) {
      return data
    }
    // 处理业务错误
    showToast({
      type: 'fail',
      message: msg || '服务器繁忙'
    })
    return Promise.reject(new Error(msg))
  },
  error => {
    // 处理HTTP错误
    const message = error?.response?.data?.message || '请求失败'

    if (error.response) {
      const status = error.response.status

      if (status === 401) {
        const userStore = useUserStore()
        userStore.clearUserInfo()

        showDialog({
          title: '提示',
          message: '登录已过期，请重新登录',
          confirmButtonText: '去登录',
        }).then(() => {
          router.push('/login')
        })
      }
    }

    showToast({
      type: 'fail',
      message
    })

    return Promise.reject(error)
  }
)

export default request